/*
 *
 *   会员功能脚本
 *   version 1.1
 *
 */
(function () {
    "use strict";

    // 用户登录
    $("#form-login").submit(function () {
        if (this.phone == '') {
            alert('手机号不能为空');
            return false;
        }
        if (this.password == '') {
            alert('登录密码不能为空');
            return false;
        }
        var url  = $(this).attr("action");
        var type = $(this).attr("method");
        var data = $(this).serialize();
        ajaxToken({
            url: url,
            type: type,
            data: data,
            success: function (result) {
                //console.log(result);
                if (result.error == 0) {
                    window.location.href = result.url;
                } else {
                    alert(result.msg);
                }
            },
            error: function (xhr, status, thrown) {
                alert("网络异常错误！");
                console.log(status);
            }
        });
        return false;
    });

    // 新用户注册发送验证码
    $("#button-register-send").click(function () {
        var url = $(this).attr("value");
        sendCode(url);
        return false;
    });

    // 找回密码发送短信验证码
    $("#form-forgot").submit(function () {
        var url = $(this).attr("code-url");
        var passwordURL = $(this).attr("password-url");
        var phone =  $("#phone").val();
        sendCode(url, function (result) {
            if (result.error == 0) {
                // 跳转到修改密码页
                window.location.href = passwordURL + '?phone=' + phone;
            } else {
                alert(result.msg);
            }
        })
        return false;
    });

    // 重新获取验证码
    $('#button-reset-send').click(function () {
        
    });

})();

/**
 * 刷新图形验证码
 */
function captchaImage(id) {
    $("#" + id).attr('src', function() {
        return this.src.split('?')[0] + '?' + Math.random()
    });
}

/**
 * 发送短信验证码
 * @param obj
 * @returns {boolean}
 */
function sendCode(url, callback) {
    var phone = $("#phone").val();
    if (!phone) {
        alert('手机号不能为空');
        return false;
    }
    var captcha = $("#captcha").val();
    if (!captcha) {
        alert('图像验证码不能为空');
        return false;
    }
    ajaxToken({
        url: url,
        data: {
            'phone': phone,
            'captcha': captcha
        },
        success: function (result) {
            //console.log(result);
            if (callback != undefined) {
                callback(result);
            } else {
                alert(result.msg);
            }
        }
    });
}